package com.elock.service.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.elock.base.core.Filter;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.NativeDao;
import com.elock.base.core.service.impl.BaseServiceImpl;
import com.elock.base.core.util.WebUtils;
import com.elock.dao.ElectronicFenceDao;
import com.elock.entity.ElectronicFence;
import com.elock.entity.SystemParameter;
import com.elock.entity.Terminal;
import com.elock.entity.TerminalElectronicFence;
import com.elock.service.ElectronicFenceService;
import com.elock.service.SystemParameterBaseService;
import com.elock.service.TerminalElectronicFenceService;
import com.elock.service.TerminalService;

/**
 * 电子围栏
 * 
 * @author 仁德
 */
@Service("electronicFenceServiceImpl")
public class ElectronicFenceServiceImpl extends BaseServiceImpl<ElectronicFence>
		implements ElectronicFenceService {

	@Resource(name = "terminalElectronicFenceServiceImpl")
	private TerminalElectronicFenceService terminalElectronicFenceService;
	@Resource(name = "terminalServiceImpl")
	private TerminalService terminalService;
	@Resource(name = "systemParameterBaseServiceImpl")
	private SystemParameterBaseService systemParameterService;
	@Resource(name = "nativeDao")
	private NativeDao nativeDao;
	@Resource(name = "electronicFenceDao")
	private ElectronicFenceDao electronicFenceDao;

	public void saveUpdate(ElectronicFence electronicFence, Long[] terminalId,
			Long saleOrgId) {

		if (electronicFence.getType() == 0) {
			electronicFence.setPoints(null);
		}
		else {
			electronicFence.setRadius(null);
			electronicFence.setLatitude(null);
			electronicFence.setLongitude(null);
		}

		if (electronicFence.getId() == null) {
			this.save(electronicFence);
		}
		else {
			this.update(electronicFence);
		}

		// 保存电子围栏与机构的关联
		if (saleOrgId != null) {
			saveElectronicFenceSaleOrg(electronicFence.getId(), saleOrgId);
		}

		// 电子围栏终端设备关联
//		if (terminalId != null) {
		saveTerminalElectronicFence(terminalId, electronicFence);
//		}
	}

	/***
	 * 保存电子围栏与机构的关联
	 * 
	 * @param electronicFence
	 * @param saleOrgId
	 */
	public void saveElectronicFenceSaleOrg(Long electronicFenceId, Long saleOrgId) {
		String sql = "replace into electronic_fence_sale_org (electronic_fence_id,sale_org_id,create_date,modify_date,company_info_id) values (?,?,now(),now(),?)";
		nativeDao.insert(sql,
				new Object[] { electronicFenceId,
						saleOrgId,
						WebUtils.getCurrentCompanyInfoId() });
	}

	/***
	 * 校验终端关联电子围栏数量
	 * 
	 * @param terminalId
	 * @param electronicFenceId
	 * @return
	 */
	public String check(Long[] terminalId, Long electronicFenceId) {
		SystemParameter sp = systemParameterService
				.getAdminParam("terminalElectronicFences");
		int num = 8;
		if (sp != null && sp.getValue() != null && !sp.getValue().equals("")) {
			try {
				num = Integer.parseInt(sp.getValue());
			}
			catch (Exception e) {}
		}
		StringBuffer ts = new StringBuffer();
		Object object[];
		if (electronicFenceId != null) {
			object = new Object[terminalId.length + 2];
		}
		else {
			object = new Object[terminalId.length + 1];
		}
		for (int i = 0; i < terminalId.length; i++) {
			ts.append("?,");
			object[i] = terminalId[i];
		}

		ts.deleteCharAt(ts.length() - 1);
		String sql = "SELECT CONCAT(terminal_num,',') FROM terminal_electronic_fence WHERE "
				+ "terminal_id IN ("
				+ ts
				+ ") ";

		if (electronicFenceId != null) {
			object[terminalId.length] = electronicFenceId;
			object[terminalId.length + 1] = num;
			sql += " AND electronic_fence_id != ? ";
		}
		else {
			object[terminalId.length] = num - 1;
		}
		sql += " GROUP BY terminal_num HAVING COUNT(1) > ?";
		String check = nativeDao.findString(sql, object);
		if (check != null) {
			check = "以下终端设备关联电子围栏数量已超过  " + num + " [" + check + "]";
		}
		else {
			check = "";
		}
		return check;
	}

	/**
	 * 保存电子围栏终端设备关联
	 */
	public void saveTerminalElectronicFence(Long[] terminalId,
			ElectronicFence electronicFence) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("electronicFenceId", electronicFence.getId()));
		List<TerminalElectronicFence> terminalElectronicFences = terminalElectronicFenceService
				.findList(null, filters, null);
		List<Long> oTerminalIds = new ArrayList<Long>();
		for (TerminalElectronicFence terminalElectronicFence : terminalElectronicFences) {
			oTerminalIds.add(terminalElectronicFence.getTerminalId());
		}

		List<Long> nTerminalIds = new ArrayList<Long>();
		if (terminalId != null && terminalId.length > 0) {
			for (Long nTerminalId : terminalId) {
				nTerminalIds.add(nTerminalId);
			}
		}

		for (Long nTerminalId : nTerminalIds) {
			if (!oTerminalIds.contains(nTerminalId)) {
				TerminalElectronicFence fence = new TerminalElectronicFence();
				fence.setTerminalId(nTerminalId);
				Terminal terminal = terminalService.find(nTerminalId);
				fence.setTerminalNum(terminal.getTerminalNum());
				fence.setElectronicFenceId(electronicFence.getId());
				terminalElectronicFenceService.save(fence);
			}
		}

		for (TerminalElectronicFence fence : terminalElectronicFences) {
			if (!nTerminalIds.contains(fence.getTerminalId())) {
				terminalElectronicFenceService.delete(fence);
			}
		}
	}

	public Page<Map<String, Object>> findPage(String name, Integer type, Long saleOrgId,
			String startTime, String endTime, Pageable pageable) {
		return electronicFenceDao.findPage(name,
				type,
				saleOrgId,
				startTime,
				endTime,
				pageable);
	}
}
